package com.sbio.udiapp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sbio.udiapp.cpcl.Bluetooth;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BtActivity extends FragmentActivity {

    @BindView(R.id.recy_history)
    RecyclerView recyHistory;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.activity_bt)
    RelativeLayout activityBt;
    private Context mContext;
    private ListView list_bt;
    public BluetoothAdapter myBluetoothAdapter;
    private Intent intent;
    private BaseQuickAdapter<BluetoothDevice, BaseViewHolder> baseQuickAdapter;
    private List<BluetoothDevice> list;
    private int tag;
    private Bluetooth bluetooth;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bt);
        ButterKnife.bind(this);
        mContext = getApplicationContext();
        recyHistory = findViewById(R.id.recy_history);
        swipeRefresh = findViewById(R.id.swipe_refresh);
        activityBt = findViewById(R.id.activity_bt);
        initData();
    }

    private void initData() {
        intent = getIntent();
        tag = intent.getIntExtra("TAG", RESULT_CANCELED);
        ListBluetoothDevice();
    }

    @SuppressLint("MissingPermission")
    public void ListBluetoothDevice() {
        if ((myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()) == null) {
            Toast.makeText(this, "没有找到蓝牙适配器", Toast.LENGTH_LONG).show();
            return;
        }

        if (!myBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 2);
            /*registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    Intent data = result.getData();
                    int resultCode = result.getResultCode();
                }
            }).launch(enableBtIntent);*/
        }
        list = new ArrayList<BluetoothDevice>();
        baseQuickAdapter = new BaseQuickAdapter<BluetoothDevice, BaseViewHolder>(android.R.layout.simple_list_item_2, list) {

            @Override
            protected void convert(BaseViewHolder helper, BluetoothDevice item) {
                if (item != null) {
                    if (item.getName() != null)
                        helper.setText(android.R.id.text1, item.getName().isEmpty() ? "Null" : item.getName());
                    helper.setText(android.R.id.text2, item.getAddress());
                }
            }
        };
        recyHistory.setLayoutManager(new LinearLayoutManager(mContext));
        recyHistory.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL));

        recyHistory.setAdapter(baseQuickAdapter);
        bluetooth = Bluetooth.getBluetooth(this);
        initBT();

        baseQuickAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bluetooth.setOnBondState(list.get(position), new Bluetooth.OnBondState() {
                    @Override
                    public void bondSuccess() {
                        if (progressDialog != null && progressDialog.isShowing())
                            progressDialog.dismiss();
                        Intent intent = new Intent();
                        intent.putExtra("SelectedBDAddress", list.get(position).getAddress());
                        intent.putExtra("SelectedBDName", list.get(position).getName());

                        setResult(tag, intent);
                        Log.i("tag111", "1");
                        finish();
                    }
                });
                if (list.get(position).getBondState() == BluetoothDevice.BOND_BONDED) {
                    Intent intent = new Intent();
                    intent.putExtra("SelectedBDAddress", list.get(position).getAddress());
                    intent.putExtra("SelectedBDName", list.get(position).getName());
                    setResult(tag, intent);
                    Log.i("tag111", tag + "");

                    finish();
                } else {
//                    Method method = null;
//                    try {
//                        method = BluetoothDevice.class.getMethod("createBond");
//                        Log.d("Print", "开始配对");
//                        method.invoke(list.get(position));
//                    } catch (Exception e) {
//                    }
                    progressDialog = new ProgressDialog(BtActivity.this);
                    //todo
//                    progressDialog.setMessage(getString(R.string.activity_devicelist_connect));
                    progressDialog.show();
                    Log.i("tag111", "2");

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            list.get(position).createBond();
                        }
                    }).start();
                }
            }
        });

        swipeRefresh.setColorSchemeResources(R.color.purple_500);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initBT();
                if (swipeRefresh.isRefreshing())
                    swipeRefresh.setRefreshing(false);
            }
        });
    }

    private void initBT() {
        Log.d("TAG", "initBT:");
        list.clear();
        baseQuickAdapter.notifyDataSetChanged();
        bluetooth.doDiscovery();
        bluetooth.getData(new Bluetooth.toData() {
            @Override
            public void succeed(BluetoothDevice bluetoothDevice) {
                for (BluetoothDevice printBT : list) {
                    if (bluetoothDevice.getAddress().equals(printBT.getAddress())) {
                        return;
                    }
                }
                //XiangYinBao_X3,ATOL1
                list.add(bluetoothDevice);
                baseQuickAdapter.notifyDataSetChanged();
            }
        });

        /*BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
        BluetoothLeScanner bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();

        ActivityCompat.requestPermissions(BtActivity.this, new String[]{
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.BLUETOOTH,
//                        Manifest.permission.BLUETOOTH_SCAN,
                Manifest.permission.ACCESS_FINE_LOCATION
        }, 123);

        ScanCallback scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                BluetoothDevice device = result.getDevice();

                String deviceName = device.getName();
                String deviceAddress = device.getAddress();
                // 在这里处理扫描到的蓝牙LE设备信息
                list.add(device);
                baseQuickAdapter.notifyDataSetChanged();
            }
        };
        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

        List<ScanFilter> filters = new ArrayList<>();*/
// 您可以添加过滤器来过滤特定的蓝牙设备
        /*if (ActivityCompat.checkSelfPermission(BtActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            ActivityCompat.requestPermissions(BtActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, 123);
            return;
        }*/

//        bluetoothScanner.startScan(filters, settings, scanCallback);
    }

    /*@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 123) {
            // 处理 ACCESS_FINE_LOCATION 权限请求的响应
            // ...
            System.out.println(123);
        }
    }*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetooth != null)
            bluetooth.disReceiver();
    }
}
